package com.hl.godsent.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.os.Environment
import android.util.Log
import com.hl.godsent.constant.AppConfig
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException


/**
 * Created by ysp
 * on 2020/12/6
 */
object ImageCompressUtils {
    /**
     *
     * @description 将图片从本地读到内存时，即图片从File形式变为Bitmap形式
     * 特点：通过设置采样率，减少图片的像素，达到对内存中的Bitmao进行压缩
     * 方法说明: 该方法就是对Bitmap形式的图片进行压缩, 也就是通过设置采样率, 减少Bitmap的像素, 从而减少了它所占用的内存
     * @param srcPath
     * @return
     */
    fun getFileFromMediaUri(ac: Context, uri: Uri): File? {
        if (uri.scheme.toString().compareTo("content") == 0) {
            val cr = ac.contentResolver
            val cursor = cr.query(uri, null, null, null, null) // 根据Uri从数据库中找
            if (cursor != null) {
                cursor.moveToFirst()
                val filePath = cursor.getString(cursor.getColumnIndex("_data")) // 获取图片路径
                cursor.close()
                if (filePath != null) {
                    return File(filePath)
                }
            }
        } else if (uri.scheme.toString().compareTo("file") == 0) {
            return File(uri.toString().replace("file://", ""))
        }
        return null
    }
    fun compressBmpFromBmp(srcPath: String?): File? {
        val newOptions = BitmapFactory.Options()
        newOptions.inJustDecodeBounds = true //只读边，不读内容
        var bitmap = BitmapFactory.decodeFile(srcPath, newOptions)
        newOptions.inJustDecodeBounds = false

        Log.i("TAG", "🔥🌹🌹 newOptions： $newOptions")
        val w = newOptions.outWidth
        val h = newOptions.outHeight
        val hh = 1600f
        val ww = 1600f
        var be = 1
        Log.i("TAG", "🔥🌹🌹 newOptions： ${newOptions.outWidth} ${newOptions.outHeight}")
        if (w > h && w > ww) {
            be = (newOptions.outWidth / ww).toInt()
        } else if (w < h && h > hh) {
            be = (newOptions.outHeight / hh).toInt()
        }
        Log.i("TAG", "🔥🌹🌹 newOptions： $be")

        if (be <= 0) be = 1
        newOptions.inSampleSize = be //设置采样率
        newOptions.inPreferredConfig = Bitmap.Config.ARGB_8888 //该模式是默认的，可不设
        newOptions.inPurgeable = true //同时设置才会有效
        newOptions.inInputShareable = true //当系统内存不够时候图片会自动被回收
        Log.i("TAG", "🔥🌹🌹 newOptions： $bitmap")
        bitmap = BitmapFactory.decodeFile(srcPath, newOptions)
//        val degree = readPictureDegree(srcPath)
//        bitmap = rotateBitmap(bitmap, degree)
        return compressBmpToFile(bitmap)
    }

    /**
     *
     * @description 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,
     * 特点是: File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变
     * 所谓的质量压缩，即为改变其图像的位深和每个像素的透明度，也就是说JPEG格式压缩后，原来图片中透明的元素将消失，所以这种格式很可能造成失真
     * @param bmp
     */
    fun compressBmpToFile(bmp: Bitmap?): File? {
        val path = AppConfig.DEFAULT_SAVE_APK_PATH + "/compressImgs/"
        val file = File(path + System.currentTimeMillis() + ".jpg")
        //判断文件夹是否存在,如果不存在则创建文件夹
        Log.i("TAG", "🌹🚀1 ${file} ${file.parentFile?.exists()} ${file.exists()} ${!file.parentFile?.exists()!!}")
        Log.i("TAG", "🌹🚀2 ${path}")
        if (!file.parentFile?.exists()!!) {
            file.parentFile?.mkdirs()
        }
        Log.i("TAG", "🌹🚀1 ${file} ${file.parentFile?.exists()} ${file.exists()}")

        val baos = ByteArrayOutputStream()
        var options = 100
        bmp!!.compress(Bitmap.CompressFormat.JPEG, options, baos)
        Log.i("TAG", "🌹🚀3 ${baos.toByteArray().size}")

        while (baos.toByteArray().size / 1024 > 100) {
            baos.reset()
            options -= 10
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos)
        }
        try {
            val fos = FileOutputStream(file)
            fos.write(baos.toByteArray())
            fos.flush()
            fos.close()
            Log.i("TAG", "🌹🚀4 ${file.absolutePath}")
            return file
        } catch (e: FileNotFoundException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        } catch (e: IOException) {
                // TODO Auto-generated catch block
            e.printStackTrace()
        }
        return null
    }

    /**
     * 获取图片旋转角度
     * @param srcPath
     * @return
     */
    private fun readPictureDegree(srcPath: String): Int {
        var degree = 0
        try {
            val exifInterface = ExifInterface(srcPath)
            val orientation: Int = exifInterface.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL
            )
            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90
                ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180
                ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return degree
    }

    //处理图片旋转
    private fun rotateBitmap(bitmap: Bitmap?, rotate: Int): Bitmap? {
        if (bitmap == null) return null
        val w = bitmap.width
        val h = bitmap.height

        // Setting post rotate to 90
        val mtx = Matrix()
        mtx.postRotate(rotate.toFloat())
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true)
    }
}